﻿using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System;
using System.Threading;
using System.Collections.Generic;

public class UdpCheck : MonoBehaviour {

    UdpClient sender;
    int remotePort = 11001;

    int localPort = 11002;
    string myIP;



    Thread receivingThread;

    public List<string> remoteIps = new List<string>();

    void Start()
    {

        sender = new UdpClient (localPort, AddressFamily.InterNetwork);
        IPEndPoint groupEP = new IPEndPoint (IPAddress.Broadcast, remotePort);
        sender.Connect (groupEP);

        myIP = GetLocalIPAddress();

        //SendData ();
        InvokeRepeating("SendData",0,2f);

        receivingThread = new Thread(StartReceivingIP);
        receivingThread.Start();
    }
    void SendData ()
    {
//        string customMessage = myName+" * "+myIP+" * "+myGameName;

        string customMessage =  myIP;
        if (customMessage != "") {
            sender.Send (Encoding.ASCII.GetBytes (customMessage), customMessage.Length);
        }
    }

    public static string GetLocalIPAddress()
    {
        var host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (var ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                return ip.ToString();
            }
        }
        return null;
//        throw new Exception("Local IP Address Not Found!");
    }


    UdpClient receiver;

    public void StartReceivingIP ()
    {


//        while(true)
//        {

            try {
                if (receiver == null) {
                    receiver = new UdpClient (remotePort);
                    receiver.BeginReceive (new AsyncCallback (ReceiveData), null);
                }
            } catch (SocketException e) {
                Debug.Log (e.Message);
            }
//            Thread.Sleep(1000);
//        }
    }



    private void ReceiveData (IAsyncResult result)
    {
        IPEndPoint receiveIPGroup = new IPEndPoint (IPAddress.Any, remotePort);
        byte[] received;
        if (receiver != null) {
            received = receiver.EndReceive (result, ref receiveIPGroup);
        } else {
            return;
        }
        receiver.BeginReceive (new AsyncCallback (ReceiveData), null);
        string receivedString = Encoding.ASCII.GetString (received);

        if(!remoteIps.Contains(receivedString)&&receivedString!=myIP)
        {
            Debug.Log(receivedString);
            remoteIps.Add(receivedString);

        }
    }



    void OnDestroy()
    {
        receivingThread.Abort();
    }

}
